<!-- 月产量统计 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <JTable
          :objectSpanObj="objectSpanMethod(tableData)"
          :tableHeader="tableHeader"
          :tableData="tableData"
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
          :headerStyle="headerStyle"
        />
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import { selectList } from '@/plugins/mixin'
import { debounce } from 'lodash'
import service from '@/utils/request'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'MonthlyOutput'
})
</script>

<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { onMounted, ref, watch } from 'vue'
const headerStyle = { 'background-color': '#CCFFFF', color: 'red', fontSize: '15px', padding: '0', height: '30px' }
console.log(headerStyle)

const currentDate = ref('')
const currentTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  currentDate.value = `${year}` // 返回格式为 YYYY-MM-DD
}
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入年度',
    inputValue: currentDate,
    inputLabel: '年度'
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '导出'
  }
])
// 表一模块
const tableHeader = ref([
  {
    prop: 'prodStep',
    label: '单位'
  },
  {
    backgroundColor: true,
    prop: 'deptName',
    label: '部门'
  },
  {
    backgroundColor: true,
    prop: 'prodQtyCount',
    label: '年度合计'
  }
])
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '导出') {
    const res = (await fileRequest.get(`/GenerateProdReport/exportMonthProd?year=${formList.value[0].inputValue}`)) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`filename=`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件a
    link.click()
    document.body.removeChild(link)
  }
}
const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.get<any, any>(`/GenerateProdReport/getMonthProd?year=${formList.value[0].inputValue}`)
  isLoading.value = false
  tableHeader.value.splice(3, tableHeader.value.length)
  tableDataList.headList.forEach((item: any, index: any) => {
    tableHeader.value.push({
      backgroundColor: true,
      prop: 'prodQty' + (index + 1),
      label: item
    })
  })
  tableData.value = tableDataList.bodyList.map((item: any) => {
    if (item.deptName === '合计') {
      item.backgroundColor = '#FFCC99'
    }
    return item
  })
  total.value = tableDataList.total
  currentRow()
  const res = objectSpanMethod(tableData.value)
  console.log(res)
}, 500)
// 合并规则
const objectSpanMethod = (tableData: any) => {
  let spanArr: any[] = []
  let pos = 0
  let prodStepMap = new Map()

  // 遍历数据，找出相同单位的行
  tableData.forEach((item: any, index: any) => {
    if (index === 0) {
      spanArr.push(1)
      pos = 0
      prodStepMap.set(item.prodStep, [index])
    } else {
      // 如果当前行的单位和上一行相同
      if (item.prodStep === tableData[index - 1].prodStep) {
        spanArr[pos] += 1
        spanArr.push(0)
        prodStepMap.get(item.prodStep).push(index)
      } else {
        spanArr.push(1)
        pos = index
        prodStepMap.set(item.prodStep, [index])
      }
    }
  })
  return ({ row, column, rowIndex, columnIndex }: any) => {
    if (columnIndex === 0) {
      // 只合并第一列（单位列）
      const rowspan = spanArr[rowIndex]
      const colspan = rowspan > 0 ? 1 : 0
      return {
        rowspan,
        colspan
      }
    }
  }
}
onMounted(() => {
  getTableList()
  currentTime()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0]) => {
  currentTableRow.value = row
}
</script>
<style lang="less" scoped>
.el-table__header {
  :deep(.cell) {
    background-color: '#CCFFFF' !important;
  }
}

table {
  table-layout: auto !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>
